<template>
  <div class="page-container">
    <div class="top-row">
      <div class="top-info" v-if="SaleroiStatus == 'statis'">
        <span class="span1 m-r2">总营业额</span>
        <span class="span2">{{ totalTurnover }}</span>
        <span class="span1 m-r6"> 元</span>
        <span class="span1 m-r2">总利润</span>
        <span class="span2">{{ totalProfit }}</span>
        <span class="span1 m-r6"> 元</span>
      </div>
      <div class="top-info" v-if="SaleroiStatus == 'roi'">
        <span class="span1 m-r2">投产比</span>
        <span class="span2">{{ Saleroi }}</span>
        <!-- <span class="span1 m-r6"> 元</span> -->
      </div>
      <div class="legend-wrapper">
        <div v-for="(legendItem, index) in legendData" :key="index" class="legend-item"
          @click="toggleSeriesVisibility(index)" :class="{ 'legend-item-hidden': !seriesVisibility[index] }">
          <span :style="{
            background: legendColors[index],
            color: 'none',
            width: '8px',
            height: '8px',
            display: 'inline-block',
            verticalAlign: 'text-top',
            lineHeight: '8px'
          }">
          </span>
          <span>{{ legendItem }}</span>
        </div>
      </div>
    </div>
    <div class="chart-container">
      <div ref="chartRef" style="width: 100%; padding: 0;" :style="{ height: eachartheight }"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, defineExpose } from 'vue';
import * as echarts from 'echarts';
const eachartheight = ref('287px' as any)
const chartRef = ref<HTMLDivElement | null>(null);
const chartInstance = ref(null as any);
const chartData = ref<{ xaxis: string[], series: { name: string, data: number[] }[] }>({
  xaxis: [],
  series: [],
});
const SaleroiStatus = ref('statis')
const Saleroi = ref('')
const totalTurnover = ref(0);
const totalProfit = ref(0);
const mealTimesName = ref('');
const legendData = ref<string[]>([]);
const legendColors = ref<string[]>([]);
const seriesVisibility = ref<boolean[]>([]);

const getChartOption = () => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        let tooltipStr = `${params.name}（${mealTimesName.value}）<br/>`;
        chartData.value.series.forEach((series, index) => {
          const colorDot = `<span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: ${legendColors.value[index]}; margin-right: 5px;"></span>`;
          const value = series.data[params.dataIndex];
          tooltipStr += `${colorDot}${series.name}: ${value} ${SaleroiStatus.value == 'statis' ? '元' : '%'}<br/>`;
        });
        return tooltipStr;
      },
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '54px',
      right: '4%',
      top: '10%',
    },
    legend: {
      show: false
    },
    xAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: chartData.value.xaxis,
        axisLabel: {
          formatter: function (value) {
            return value;
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: SaleroiStatus.value == 'statis' ? '金额 (元)' : '投产比 %',
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            width: 1
          }
        },
        nameTextStyle: {

          padding: [0, 0, 0, -40] // 左padding负值，向左移动

        },
        axisLabel: {

          align: 'right',

          margin: 0 // 调整标签与轴的距离

        },
        offset: 10
      }
    ],
    series: chartData.value.series.map((series, index) => ({
      name: series.name,
      type: 'line',
      barWidth: '6px',
      itemStyle: {
        color: legendColors.value[index]
      },
      data: series.data
    }))
  };
};

const initChart = async (row) => {
  console.log(row, '2')
  if (chartRef.value) {
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = null;
    }
    // 设置新高度
    eachartheight.value = row.height ? row.height : '289px';
    // 等待 DOM 更新
    await nextTick(); // ⚠️ 关键点：确保高度已应用到 DOM
    SaleroiStatus.value = row.SaleroiStatus
    chartInstance.value = echarts.init(chartRef.value);
    chartData.value = {
      xaxis: row.xaxis,
      series: row.series.map(item => ({
        name: item.name,
        data: item.data || []
      }))
    };
    mealTimesName.value = row.mealTimesName;

    // 动态生成图例和颜色
    legendData.value = chartData.value.series.map(series => series.name);
    // legendColors.value = chartData.value.series.map(() => getRandomColor());
    if (row.SaleroiStatus == 'roi') {
      legendColors.value = ['rgba(13, 162, 231, 1)']
      Saleroi.value = row.extra.roi
    } else {
      legendColors.value = ['rgba(20, 184, 165, 1)', 'rgba(255, 87, 106, 1)']
      totalTurnover.value = row.extra.totalSaleAmount;
      totalProfit.value = row.extra.totalProfitAmount;
    }
    seriesVisibility.value = chartData.value.series.map(() => true);

    // totalTurnover.value = row.extra.totalSaleAmount;
    // totalProfit.value = row.extra.totalProfitAmount;

    const option = getChartOption();
    chartInstance.value.setOption(option, true);
    // 立即调整图表尺寸
    // chartInstance.value.resize(); // ⚠️ 确保图表适应新高度
  }
};
watch(chartData, () => {
  if (chartInstance.value) {
    const option = getChartOption();
    chartInstance.value.setOption(option);
  }
}, { deep: true });
// 生成随机颜色
const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};

const toggleSeriesVisibility = (index: number) => {
  if (!chartInstance.value) return;

  const seriesName = legendData.value[index];
  chartInstance.value.dispatchAction({
    type: 'legendToggleSelect',
    name: seriesName
  });
  seriesVisibility.value[index] = !seriesVisibility.value[index];
};

defineExpose({
  initChart
});

onMounted(() => {
  // initChart();
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;

  .span1 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.65);
  }

  .span2 {
    font-family: DIN, DIN;
    font-weight: bold;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    margin-right: 2px;
  }
}

.top-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.top-info {
  display: flex;
  align-items: center;
}

.chart-container {
  width: 100%;
}

.legend-wrapper {
  display: flex;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background: rgba(0, 0, 0, 0.04);
  }

  &-hidden {
    span:first-child {
      filter: grayscale(100%) brightness(1.5);
      opacity: 0.6;
    }

    span:last-child {
      color: #999 !important;
      position: relative;
    }
  }
}
</style>